
package controllers;

import play.data.*;
import play.mvc.*;
import models.*;
import views.html.classifiche.*;

public class Classifiche extends Controller {
	
	static Form<Classifica> classificaForm = Form.form(Classifica.class);

	//SHOW
	@Security.Authenticated(Secured.class)
	public static Result classifiche() {
		return ok(classifica.render(Classifica.all(),classificaForm,false,false));
	}
	  
	//NEW
	@Security.Authenticated(SecuredWriter.class)
	public static Result newClassifica() {
		Form<Classifica> filledForm = classificaForm.bindFromRequest();
		  if(filledForm.hasErrors()) {
			  return badRequest(nuova_classifica.render( filledForm,false));
		  } 
		  else {
			  if(!Classifica.create(filledForm.get())){
				  return ok(nuova_classifica.render( filledForm,true)); 
			  }
			  
			  return ok(classifica.render(Classifica.all(), classificaForm,false,true));
		  }
	}
	
	//DELETE
	@Security.Authenticated(SecuredWriter.class)
	public static Result deleteClassifica(Long id) {
		if(!Classifica.delete(id)){
			return ok(classifica.render(Classifica.all(), classificaForm,true,false));
		}
		return ok(classifica.render(Classifica.all(), classificaForm,false,true));
	}
	
	//EDIT
	@Security.Authenticated(SecuredWriter.class)	
	public static Result editClassifica(Long id) {
		
		Classifica daModificare=Classifica.find.byId(id);
				    	    
	    Form<Classifica> filledForm = Form.form(Classifica.class).bindFromRequest();
	    
		if(filledForm.hasErrors()) {
			if(Classifica.update(daModificare)){
				return badRequest(edit_classifica.render(Classifica.all(), filledForm.fill(Classifica.find.byId(daModificare.id)),id,daModificare,false));
			}
			else return redirect(routes.Classifiche.classifiche());
		}
	   	else{
	   			daModificare.id=id;
	   			daModificare.tettoBudget=filledForm.get().tettoBudget;
	    		
	   			if(!Classifica.update(daModificare)){
	   				return ok(edit_classifica.render(Classifica.all(), filledForm.fill(Classifica.find.byId(daModificare.id)),id,daModificare,true));
	   			}
	    		
	   			return ok(classifica.render(Classifica.all(), classificaForm,false,true));
		} 
		
	}

}